<?php
/**
 * Created by PhpStorm.
 * User: qhzhyt
 * Date: 2018/10/5
 * Time: 17:44
 */

//var_dump($_FILES);
if (!isset($_POST['mapName']) || !isset($_FILES['map'])) {
    echo(json_encode(['status' => 0, 'code' => 2]));
    exit(1);
}
session_start();
if (!isset($_SESSION['user'])) {
    echo(json_encode(['status' => 0, 'code' => -1]));
    exit(1);
}
$map = $_FILES['map'];
$user = $_SESSION['user'];
if (!is_uploaded_file($map['tmp_name'])) {
    echo(json_encode(['status' => 0, 'code' => 2]));
    exit(1);
}
$file_hash = md5_file($map['tmp_name']);
require_once '../conf/conf.php';
$db->insert('map', ['user_id' => $user['user_id'], 'map_name' => $_POST['mapName'], 'map_hash' => $file_hash]);
$mapId = $db->id();
if ($mapId == 0) {
    echo(json_encode(['status' => 0, 'code' => 9]));
    exit(1);
}

$exp = $user['maker_exp'];

$level = $user['maker_level'];

$exp += 5;
$need = pow(2, $level) * 5;

if ($exp >= $need) {
    $exp -= $need;
    $user['maker_level'] = $level + 1;
}

$user['maker_exp'] = $exp;
$user['upload_count'] = $user['upload_count'] + 1;

$db->update('user', [
    'maker_exp' => $user['maker_exp'],
    'maker_level' => $user['maker_level'],
    'upload_count' => $user['upload_count']
], ['user_id' => $user['user_id']]);

move_uploaded_file($map['tmp_name'], '../files/upload/map/map_' . $mapId . '_' . substr($file_hash, 16) . '.json');
if (isset($_FILES['cover'])) {
    $cover = $_FILES['cover'];
    if (!is_uploaded_file($cover['tmp_name'])) {
        echo(json_encode(['status' => 1, 'code' => 1]));
        exit(1);
    }
    move_uploaded_file($cover['tmp_name'], '../files/upload/cover/cover_' . $mapId . '_' . substr($file_hash, 16) . '.png');
    echo(json_encode(['status' => 1, 'code' => 1]));
}